package com.qingge.springboot.controller;

import com.qingge.springboot.common.Result;
import com.qingge.springboot.controller.dto.CourseTeacherVo;
import com.qingge.springboot.controller.dto.UserDTO;
import com.qingge.springboot.entity.StudentCourse;
import com.qingge.springboot.entity.vo.FileVo;
import com.qingge.springboot.entity.work;
import com.qingge.springboot.service.CourseTeacherFileService;
import com.qingge.springboot.service.IWorkService;
import com.qingge.springboot.service.StudentService;
import com.qingge.springboot.utils.TokenUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    StudentService service;

    @Resource
    CourseTeacherFileService fileService;

    @Resource
    IWorkService workService;

    @PostMapping("/studentLogin")
    public Result studentLogin(@RequestBody HashMap<String,String> login){
        //获取账号
        String username = login.get("username");
        //获取密码
        String password = login.get("password");
        UserDTO userDTO =  service.login(username,password);
        if(StringUtils.hasLength(userDTO.getUsername())){
            String s = TokenUtils.genToken(userDTO.getUsername(), password);
            userDTO.setToken(s);
            userDTO.setAvatarUrl("");
            userDTO.setRole("ROLE_TEACHER");
            return Result.success(userDTO);
        }
        return Result.error("500","账号或密码错误");
    }

    @RequestMapping("/getCourse/{stuId}")
    public Result getStudentAndClassCourse(@PathVariable Integer stuId){
        List<CourseTeacherVo> courseTeacherVos = service.selectClassCourseByStuId(stuId);
        return Result.success(courseTeacherVos);
    }

    @GetMapping("/getKj/{id}")
    public void downloadKj(@PathVariable Integer id, HttpServletResponse response) throws IOException {
            //获取文件名称
        FileVo byId = fileService.getById(id);
        File file = new File(byId.getFileUrl());
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        response.reset();
        response.setHeader("Access-Control-Expose-Headers", "Content-Type,Content-Disposition");
        response.setContentType("application/octet-stream;charset=UTF-8;");
//            response.setHeader("Content-Disposition","attachment;filename="+filename+ ".json");
        String[] split = byId.getFileUrl().split(".");
        String hou = null;
        if(byId.getFileUrl().lastIndexOf(".")!=-1 && byId.getFileUrl().lastIndexOf(".")!=0){
            hou =   byId.getFileUrl().substring(byId.getFileUrl().lastIndexOf(".")+1);
        }
        response.setHeader( "Content-Disposition", "attachment;filename=" + new String( file.getName().getBytes("gb2312"), "ISO8859-1" ) );

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buf = new byte[1024];
        int len = 0;
        while (true) {
            try {
                if (!((len = br.read(buf))>0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.write(buf,0,len);
        }
        br.close();
        out.close();
    }


    @GetMapping("/downFile/{workId}")
    public void downFile(HttpServletResponse response, @PathVariable String workId) throws IOException {
        try {
            work byId = workService.getById(workId);
            // path是指欲下载的文件的路径。
            File file = new File(byId.getFileUrl());
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(byId.getFileUrl()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}
